package com.myzl.coal.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.myzl.coal.domain.Device;
import com.myzl.coal.domain.Statistics;
import com.myzl.coal.domain.vo.ComparisonVO;
import com.myzl.coal.mapper.DeviceMapper;
import com.myzl.coal.mapper.StatisticsMapper;
import com.myzl.coal.service.IDeviceService;
import com.myzl.coal.service.IMongoHistoryDataService;
import com.myzl.coal.service.IRealTimeDataService;
import com.myzl.coal.service.IStatisticsService;
import com.myzl.common.core.domain.AjaxResult;
import com.myzl.common.enums.DeviceTypeEnum;
import com.myzl.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 统计Service业务层处理
 *
 * @author myzl
 * @date 2022-11-16
 */
@Slf4j
@Service
public class StatisticsServiceImpl implements IStatisticsService
{
    @Autowired
    private StatisticsMapper statisticsMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IRealTimeDataService realTimeDataService;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IMongoHistoryDataService mongoHistoryDataService;

    /**
     * 查询统计
     *
     * @param id 统计主键
     * @return 统计
     */
    @Override
    public Statistics selectStatisticsById(Long id)
    {
        return statisticsMapper.selectStatisticsById(id);
    }

    /**
     * 查询统计列表
     *
     * @param statistics 统计
     * @return 统计
     */
    @Override
    public List<Statistics> selectStatisticsList(Statistics statistics)
    {
        return statisticsMapper.selectStatisticsList(statistics);
    }

    /**
     * 新增统计
     *
     * @param statistics 统计
     * @return 结果
     */
    @Override
    public int insertStatistics(Statistics statistics)
    {
        statistics.setCreateTime(DateUtils.getNowDate());
        return statisticsMapper.insertStatistics(statistics);
    }

    /**
     * 修改统计
     *
     * @param statistics 统计
     * @return 结果
     */
    @Override
    public int updateStatistics(Statistics statistics)
    {
        statistics.setUpdateTime(DateUtils.getNowDate());
        return statisticsMapper.updateStatistics(statistics);
    }

    /**
     * 批量删除统计
     *
     * @param ids 需要删除的统计主键
     * @return 结果
     */
    @Override
    public int deleteStatisticsByIds(Long[] ids)
    {
        return statisticsMapper.deleteStatisticsByIds(ids);
    }

    /**
     * 删除统计信息
     *
     * @param id 统计主键
     * @return 结果
     */
    @Override
    public int deleteStatisticsById(Long id)
    {
        return statisticsMapper.deleteStatisticsById(id);
    }

    @Override
    public boolean statistics() {
        List<Device> deviceList = deviceMapper.selectList(new LambdaQueryWrapper<Device>().eq(Device::getDeviceType, DeviceTypeEnum.DOUBLE_ORDER.getCode()));
        List<Statistics> dataList = new ArrayList<>();
        deviceList.forEach(device -> {
            Statistics statistics = new Statistics();
            String date = DateUtil.formatDate(DateUtil.yesterday());
            ComparisonVO comparison = realTimeDataService.comparison(device.getId(), date);
            BeanUtils.copyProperties(comparison,statistics);
            statistics.setDate(DateUtil.yesterday());
            statistics.setDeviceId(device.getId());
            statistics.setDeviceName(device.getDeviceName());
            dataList.add(statistics);
        });
        if (dataList.size() <= 0){
            return false;
        }
        dataList.forEach(data ->{
            int count = statisticsMapper.selectCount(new LambdaQueryWrapper<Statistics>()
                    .eq(Statistics::getDeviceId,data.getDeviceId())
                    .eq(Statistics::getDate,DateUtil.formatDate(DateUtil.yesterday())));
            if (count > 0){
                statisticsMapper.update(data,new LambdaUpdateWrapper<Statistics>()
                        .eq(Statistics::getDeviceId,data.getDeviceId())
                        .eq(Statistics::getDate,DateUtil.formatDate(DateUtil.yesterday())));
            } else {
                statisticsMapper.insert(data);
            }
        });
        return true;
    }

    @Override
    public List<Object> scaleDashboard(Integer deviceId) {
        Device scale = deviceService.selectDeviceById(deviceId);
        List<Device> ledList = deviceService.getDeviceByGroupId(scale.getDeviceGroup(),DeviceTypeEnum.LED_SCREEN.getCode());
        if (CollUtil.isEmpty(ledList)){
            log.info("没有对应LED设备");
            return new ArrayList<>();
        }
        JSONObject deviceConfig = JSON.parseObject(ledList.get(0).getDeviceConfig());
        List<Integer> contents = deviceConfig.getList("contents", Integer.class);
        return realTimeDataService.currentData(scale.getId(), contents);
    }

    @Override
    public List<Object> scaleDashboard1(Integer deviceId) {
        return realTimeDataService.currentData(deviceId);
    }
    @Override
    public List<Object> scaleDashboard1(Integer deviceId,String startTime,String endTime) {
        return realTimeDataService.currentData(deviceId,startTime,endTime);
    }

    @Override
    public AjaxResult daily(String date) {
        List<Statistics> statistics = statisticsMapper.selectList(new LambdaQueryWrapper<Statistics>().eq(Statistics::getDate, date));
        Device deviceParam = new Device();
        deviceParam.setDeviceType(DeviceTypeEnum.DOUBLE_ORDER.getCode());
        List<Device> deviceList = deviceService.selectDeviceList(deviceParam);
        List<ComparisonVO> comparisonVOList = new ArrayList<>();
        for (Device device : deviceList) {
            ComparisonVO comparisonVO = new ComparisonVO();
            for (Statistics statistic : statistics) {
                if (device.getId().equals(statistic.getDeviceId())){
                    BeanUtils.copyProperties(statistic,comparisonVO);
                }
            }
            BeanUtils.copyProperties(device,comparisonVO);
            comparisonVOList.add(comparisonVO);
        }
        return AjaxResult.success(comparisonVOList);
    }

    @Override
    public AjaxResult daily(String date, Integer deviceId) {
        Statistics statistics = statisticsMapper.selectOne(new LambdaQueryWrapper<Statistics>()
                .eq(Statistics::getDeviceId, deviceId)
                .eq(Statistics::getDate, date)
                .last("limit 1"));
        return AjaxResult.success(statistics);
    }

    @Override
    public boolean clearMongoData() {
        mongoHistoryDataService.clearOtherData();
        List<Device> scaleList = deviceMapper.selectList(new LambdaQueryWrapper<Device>()
                .eq(Device::getDeviceType, DeviceTypeEnum.DOUBLE_ORDER.getCode())
                .orderByDesc(Device::getId));
        scaleList.forEach(device -> {
            // 处理删除数据的方法
            boolean result = mongoHistoryDataService.clearScaleData(device);

        });
        return true;
    }
}
